<?php
            
use app\model\Util; 
use app\model\Theme; 
use app\model\Worker; 


/**
 * Author: cbw
 * Desc: 抖音商城项目
 * Time: 2022/7/18 10:18
 * Email: 17854288794@163.com
 */

class Index_Page extends PluginWebPage{

    function main()
    {
        $action = 'index';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;

        $sj_id = isset($_P['sj_id'])?intval($_P['sj_id']):0;
        $status = isset($_P['status'])?intval($_P['status']):-1;
        $search = isset($_P['search_data'])?$_P['search_data']:'';
        $shangjia = SjMulitVerifyModel::getShangjiaList();
        if (!$shangjia){
            return_msg('请先添加商家');
            exit();
        }
        $list_arr = $this->getSjTypeProducts($themeid,$_C);
        $status_arr = $this->getSjStatusProducts($themeid,$sj_id);
        $all_flag_total = SjMulitVerifyModel::getUserProductFlagTotal($themeid,0);
        $total = SjMulitVerifyModel::getSjProductList($themeid,$search,$status,$sj_id,0,0,true);
        $list = SjMulitVerifyModel::getSjProductList($themeid,$search,$status,$sj_id,$page_start,$page_size);
        foreach ($list as $k => $v){
            $list[$k]['flag_total'] = SjMulitVerifyModel::getUserProductFlagTotal($themeid,$v['id']);
        }
        $page_total = $total;
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/sjmulitverify/main/main', $return_clicent);
    }

    function user()
    {
        $action = 'user';
        global $_G,$_P,$_S,$_C;
        $system = $_S;
        $config = $_C;
        $themeid = intval($_P['themeid']);
        if($themeid <= 0){
            $themeid = Theme::getDefaultThemenew();
        }
        $shangjia = SjMulitVerifyModel::getShangjiaList();
        if (!$shangjia){
            return_msg('请先添加商家');
            exit();
        }
        $themelist = Theme::getAllTheme();
        $page_index = max(1,intval($_P['page']));
        $page_size = 50;
        $page_start = ($page_index-1)*$page_size;
        $sj_id = isset($_P['sj_id'])?intval($_P['sj_id']):0;
        $p_id = isset($_P['p_id'])?intval($_P['p_id']):0;
        $status = isset($_P['status'])?intval($_P['status']):0;
        $order_id = isset($_P['order_id'])?intval($_P['order_id']):0;
        $search = isset($_P['search_data'])?$_P['search_data']:'';
        $list_arr = $this->getSjUserFlag($themeid,$_C,'is_sj');
        $status_arr= $this->getSjUserFlag($themeid,$_C,'status',$sj_id,$order_id);
        $total = SjMulitVerifyModel::getUserRecordSjProductList($themeid,$search,$sj_id,$p_id,0,0,true,$status,$order_id);
        $list = SjMulitVerifyModel::getUserRecordSjProductList($themeid,$search,$sj_id,$p_id,$page_start,$page_size,false,$status,$order_id);
        if ($list && is_array($list)){
            $worklist = Worker::getworkerlist($system,$themeid);
            foreach ($list as $k => $row){
                if ($row['worker_id']){
                    $r = Worker::getWokerName($system,$themeid,$row['worker_id'],$worklist);
                    $list[$k]['workermobile'] = SjMulitVerifyModel::getWorkerMobile(['themeid'=>$themeid,'uid'=>$row['worker_id']])['mobile'];
                    $list[$k]['workername']=$r['workername'];
                    $list[$k]['teamname']=$r['teamname'];
                    $list[$k]['companyname']=$r['companyname'];
                }else{
                    $list[$k]['status']=1;
                }

            }
        }

        if(checksubmit('export_submit', true)){
            $count = $total;
            $page_limit = 2000;
            $pagesize = ceil($count/$page_limit);
            $header = array(
                'username' => '姓名', 'mobile' => '手机',
                'order_id' => '定单号','order_time' => '下单时间',
                'shangjia_name' => '商家','name' => '产品',
                'status' => '核销状态','updated_at' => '核销时间',
                'workername' => '核销人','workermobile' => '核销人电话',
            );
            $keys = array_keys($header);
            $html = "\xEF\xBB\xBF";
            foreach ($header as $li) {
                $html .= $li . "\t ,";
            }
            $html .= "\n";

              $ex_page = $_P['ex_page']?$_P['ex_page']:1;
            //for ($j = 1; $j <= $pagesize; $j++) {
                $page_start = ($ex_page - 1)*$page_limit;
                $list = SjMulitVerifyModel::getUserRecordSjProductList($themeid,$search,$sj_id,$p_id,$page_start,$page_limit,false,$status,$order_id);
                if ($list && is_array($list)){
                    $worklist = Worker::getworkerlist($system,$themeid);
                    foreach ($list as $k => $row){
                        if ($row['worker_id']){
                            $r = Worker::getWokerName($system,$themeid,$row['worker_id'],$worklist);
                            $list[$k]['workermobile'] = SjMulitVerifyModel::getWorkerMobile(['themeid'=>$themeid,'uid'=>$row['worker_id']])['mobile'];
                            $list[$k]['workername']=$r['companyname'].'-'.$r['teamname'].'-'.$r['workername'];
                        }else{
                            $list[$k]['status'] =1;
                        }
                        $list[$k]['order_id'] = 9000+(int)$row['order_id'];
                    }
                }

                if (!empty($list)) {
                    $size = ceil(count($list) / 500);
                    for ($i = 0; $i < $size; $i++) {
                        $buffer = array_slice($list, $i * 500, 500);
                        foreach ($buffer as $row) {
                            if ($row['status']==1){
                                $row['status'] = '待核销';
                                $row['updated_at'] = '';
                            }elseif ($row['status']==2){
                                $row['status'] = '已核销';
                            }

                            foreach ($keys as $key) {
                                $data[] = $row[$key];
                            }
                            if (isset($data)){
                                $user[] = implode("\t ,", $data) . "\t ,";
                                unset($data);
                            }
                        }
                        $html .= implode("\n", $user)."\n";
                        unset($user);
                    }
              //  }
             }

            //新版本导出合并
            $is_end = 0;
            if($ex_page>=$pagesize){
                $is_end = 1;
            }
            Util::WxJump($_S,$html,'商家产品-用户记录',$themeid,$is_end,$pagesize);
        }

        $pager = pagination($total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return $this->view('/sjmulitverify/main/user', $return_clicent);
    }

    function getSjTypeProducts($themeid,$_C)
    {
        $all_arr = [];
        $all_total = 0;
        $shangjia = SjMulitVerifyModel::getShangjiaList();
        if ($shangjia){
            foreach ($shangjia as $k => $val){
                $total = SjMulitVerifyModel::getSjProductTotal($themeid,$val['id']);
                $all_total+=$total;
                $tmp_arr = ['title'=>$val['name'],'total'=>$total,'id'=>$val['id']];
                array_push($all_arr,$tmp_arr);
            }
        }
        array_unshift($all_arr,['title'=>'全部','total'=>$all_total,'id'=>0]);
        return $all_arr;
    }

    function getSjStatusProducts($themeid,$sj_id=0)
    {
        $arr = [ ['title'=>'全部','total'=>0,'status'=>-1],['title'=>'下架','total'=>0,'status'=>0], ['title'=>'上架','total'=>0,'status'=>1]];
        $all_total = 0;
        foreach ($arr as $k => $v){
            $total = SjMulitVerifyModel::getSjProductStatusTotal($themeid,$v['status'],$sj_id);
            $arr[$k]['total'] = $total;
            $all_total += $total;
        }
        $arr[0]['total']=$all_total;
        return $arr;
    }

    function getSjUserFlag($themeid,$_C,$type='is_sj',$sj_id=0,$order_id=0)
    {
        $all_arr = [];
        $all_total = 0;
        if ($type=='is_sj'){
            $shangjia = SjMulitVerifyModel::getShangjiaList();
            if ($shangjia){
                foreach ($shangjia as $k => $val){
                    $tmp_total = (int)SjMulitVerifyModel::getSjProductTotal($themeid,$val['id']);
                    $order_total = (int)SjMulitVerifyModel::getOrderTotalByWhere($themeid);
                    $total = ($tmp_total * $order_total);
                    $all_total+=$total;
                    $tmp_arr = ['title'=>$val['name'],'total'=>$total,'id'=>$val['id']];
                    array_push($all_arr,$tmp_arr);
                }
            }
            array_unshift($all_arr,['title'=>'全部','total'=>$all_total,'id'=>0]);
        }elseif ($type=='status'){
            $order_total = (int)SjMulitVerifyModel::getOrderTotalByWhere($themeid);
            $product_total = (int)SjMulitVerifyModel::getSjProductStatusTotal($themeid,1,$sj_id);
            if (!$order_id){
                $all_total  = $order_total*$product_total;
            }else{
                $all_total = $product_total;
            }
            $has_total = (int)SjMulitVerifyModel::getUserProductFlagTotal($themeid,0,$sj_id,2,$order_id);
            $no_total = $all_total -$has_total;
            $all_arr = [
                ['title'=>'不限','status'=>0,'total'=>$all_total],
                ['title'=>'未核销','status'=>1,'total'=>$no_total],
                ['title'=>'已核销','status'=>2,'total'=>$has_total]];

        }

        return $all_arr;
    }

    function add()
    {
        return $this->post();
    }

    function edit()
    {
        return $this->post();
    }

    function post()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['id']);
        $themeid = $_P['themeid'];
        $shangjia = SjMulitVerifyModel::getShangjiaList();
        if ($_G['ispost']) {
            $shangjiaid = intval($_P['shangjiaid']);
            $name = trim($_P['name']);
            $top_img = isset($_P['top_img'])?tomedia($_P['top_img']):'';
            $qty = isset($_P['qty'])?trim($_P['qty']):0;
            $price = isset($_P['price'])?floatval(trim($_P['price'])):'0';
            $status = intval($_P['status']);
            $show_sort = intval($_P['show_sort']);

            if (empty($shangjiaid) || !$shangjiaid){
                show_json(0,['msg'=>'未绑定商家']);
                die();
            }
            if (empty($name) || !$name){
                show_json(0,['msg'=>'名称不能为空！']);
                die();
            }
            $data = [
                'shangjiaid'=>$shangjiaid,
                'name'=>$name,
                'top_img'=>$top_img,
                'qty'=>$qty,
                'price'=>$price,
                'status'=>$status,
                'show_sort'=>$show_sort,
                'themeid'=>$themeid,
            ];


            if (!$p_id){
                $res = SjMulitVerifyModel::insertProductItem($data);
            }else{
                $old_item = SjMulitVerifyModel::getProductItem(['id'=>$p_id,'themeid'=>$themeid]);
                unset($data['ended_at']);
                unset($data['created_at']);
                unset($data['updated_at']);
                $type = '['.$old_item['name'].']-异业产品编辑';
                writelog($themeid,$type,$old_item,$data,$_G['username']);
                $where = ['id'=>$p_id,'themeid'=>$themeid];
                $res = SjMulitVerifyModel::editProductItem($where,$data);
            }
            if (!$res){
                show_json(0,['msg'=>'操作失败']);
            }else{
                show_json(1,['msg'=>'操作成功']);
            }
        }
        else{
            if ($p_id && $themeid) {
                $item = SjMulitVerifyModel::getProductItem(['id'=>$p_id,'themeid'=>$themeid]);
            }
            $return_clicent = get_defined_vars();
return $this->view('/sjmulitverify/main/edit', $return_clicent);
        }

    }

    function delete()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['id']);
        $themeid = $_P['themeid'];
        if ($_G['ispost']) {
            $res = SjMulitVerifyModel::delProductItem(['themeid'=>$themeid,'id'=>$p_id]);
            if (!$res){
                show_json(0,['msg'=>'操作失败']);
            }else{
                show_json(1,['msg'=>'操作成功']);
            }
        }

    }

    function editItem()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $p_id = intval($_P['id']);
        $themeid = $_P['themeid'];
        $type = isset($_P['type'])?$_P['type']:"";
        if (!$type){

        }elseif ($type=='status'){
            //获取产品详情
            $item = SjMulitVerifyModel::getProductItem(['themeid'=>$themeid,'id'=>$p_id]);
            $where = ['themeid'=>$themeid,'id'=>$p_id];
            $res = [];
            if ($item && $item['status']==0){
                $data = ['status'=>1];
                $res = SjMulitVerifyModel::editProductItem($where,$data);
            }elseif ($item && $item['status']==1){
                $data = ['status'=>0];
                $res = SjMulitVerifyModel::editProductItem($where,$data);
            }
            if (!$res){
                show_json(0,['msg'=>'操作失败']);
            }else{
                show_json(1,['msg'=>'操作成功']);
            }
        }
    }

    function formatSjData()
    {
        $total = 0;
        $shangjia = SjMulitVerifyModel::getShangjiaList();
    }

    /**
     * Desc:产品模版上传
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:32
     */
    function uploadFile()
    {
        global $_G,$_P,$_S,$_C;
        $themeid = intval($_P['themeid']);
        $all_arr = [];
        $file = $_FILES['file'];
        $filename = $file['tmp_name'];
        if (empty($filename)){
            $response = ['code'=>30000,'msg'=>'请选择要导入的CSV文件！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        if (!$file['size']){
            $response = ['code'=>30000,'msg'=>'文件不能为空！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        if ($file['name'] && $file['error']==0){
            $type = substr($file['name'],strpos($file['name'],"."));
            $type = strtolower($type);
            if (!in_array($type,['.csv'])){
                $response = ['code'=>30000,'msg'=>'文件类型错误！','data'=>[]];
                return_msg($response, '', 'ajax');
            }
        }
        $handle = fopen($file['tmp_name'],'r');
        $out = array ();
        $n = 0;
        while ($data = fgetcsv($handle, 10000))
        {
            $num = count($data);
            for ($i = 0; $i < $num; $i++)
            {
                $out[$n][$i] = $data[$i];
            }
            $n++;
        }
        $result = $out;
        $len_result = count($result);
        if($len_result==0){
            $response = ['code'=>30000,'msg'=>'无数据！','data'=>[]];
            return_msg($response, '', 'ajax');
        }
        $data_values = '';
        for($i = 1; $i < $len_result; $i++) //循环获取各字段值
        {
            $shangjianame = trim($result[$i][0]);
            $name = trim($result[$i][1]);
            $shangjiaid = SjMulitVerifyModel::getSjIdByName($themeid,$shangjianame)['id'];
            $data_values .= "('$shangjiaid','$name','','1','$themeid'),";
        }
        $data_values = substr($data_values,0,-1); //去掉最后一个逗号
        fclose($handle); //关闭指针
        $sql = "INSERT INTO ".tablename(sj_mulit_products)." (`shangjiaid`, `name`, `price`,`status`,`themeid`) VALUES $data_values";//sql语句
        $res = db_query($sql);
        $response = ['code'=>200,'msg'=>'操作成功,请稍后查看！','data'=>[]];
        return_msg($response, '', 'ajax');
    }

    /**
     * Desc:产品模版下载
     * User:cbw
     * Email:17854288794@163.com
     * Time: 2022/7/18 10:31
     */
    function downLoad()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $themeid = $_P['themeid'];
        $temp_list = SjMulitVerifyModel::getShangjiaList();
        $total_arr = [];
        foreach ($temp_list as $kk => $vv){
            $tmp_arr = ['shangjianame'=>$vv['name'],'name'=>'','price'=>''];
            array_push($total_arr,$tmp_arr);
        }


        $count = count($total_arr);
        $pagesize = ceil($count/5000);
        $header = array(
            'shangjianame' => '归属商家', 'name' => '产品名称',
        );
        $keys = array_keys($header);
        $html = "\xEF\xBB\xBF";
        foreach ($header as $li) {
            $html .= $li . "\t ,";
        }
        $html .= "\n";
//        for ($j = 1; $j <= $pagesize; $j++) {
            $list = $total_arr;
            if (!empty($list)) {
                $size = ceil(count($list) / 500);
                for ($i = 0; $i < $size; $i++) {
                    $buffer = array_slice($list, $i * 500, 500);
                    foreach ($buffer as $row) {
                        foreach ($keys as $key) {
                            $data[] = $row[$key];
                        }
                        if (isset($data)){
                            $user[] = implode("\t ,", $data) . "\t ,";
                            unset($data);
                        }
                    }
                    $html .= implode("\n", $user)."\n";
                    unset($user);
                }
        //    }
        }
        //新版本导出合并
        Util::WxJump($_S,$html,'示例商家产品',$themeid,1,1);
    }

    function opType()
    {
        global $_G,$_S,$_C,$_P;
        $system = $_S;
        $config = $_C;
        $themeid = $_P['themeid'];
        $type = isset($_P['type'])?$_P['type']:"";
        $where = ['themeid'=>$themeid];
        $res = [];
        if (!$type){
            show_json(0,['msg'=>'操作失败']);
        }elseif ($type=='out'){
            //上架所有
            $data = ['status'=>1];
            $res = db_update(sj_mulit_products,$data,$where);
        }elseif ($type=='in'){
            //下架所有
            $data = ['status'=>0];
            $res = db_update(sj_mulit_products,$data,$where);
        }elseif ($type=='del'){
            //删除所有
            $res = db_delete(sj_mulit_products,$where);
        }
        if (!$res){
            show_json(0,['msg'=>'操作失败']);
        }else{
            show_json(1,['msg'=>'操作成功']);
        }
    }
}